﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;

using Microsoft.Phone.Tasks;

using System.Net.Sockets;
using System.Text;
using System.IO;
using Microsoft.Phone;
using System.Net.NetworkInformation;

using sdkMulticastCS;

// Barcode
using WP7_Barcode_Library;
using WP7_Common_Code;
using System.Windows.Threading;


namespace WirelessBarcodeReader
{
    public partial class MainPage : PhoneApplicationPage
    {
        CameraCaptureTask cameraCaptureTask = new CameraCaptureTask();
        WebBrowserTask webBrowserTask = new WebBrowserTask();
        private string code128 = string.Empty;

        // The address of the multicast group to join.
        // Must be in the range from 224.0.0.0 to 239.255.255.255
        private const string GROUP_ADDRESS = "224.0.1.12";

        // The port over which to communicate to the multicast group
        private const int GROUP_PORT = 54329;

        // true if we have joined the multicast group; otherwise, false
        bool _joined = false;

        // Maximum size of a message in this communication
        private const int MAX_MESSAGE_SIZE = 1024;

        private UdpAnySourceMulticastChannel Channel { get; set; }

        DispatcherTimer sendingTimer = new DispatcherTimer();

        public MainPage()
        {
            InitializeComponent();
            cameraCaptureTask.Completed += new EventHandler<PhotoResult>(cameraCaptureTask_Completed);

            WP7BarcodeManager.ScanMode = com.google.zxing.BarcodeFormat.CODE_128;

            sendingTimer.Tick += new EventHandler(dispatcherTimer_Tick);
            sendingTimer.Interval = new TimeSpan(0, 0, 2);
        }

        protected override void OnNavigatingFrom(System.Windows.Navigation.NavigatingCancelEventArgs e)
        {
            sendingTimer.Stop();
            this.Channel.Close();
            this._joined = false;
        }

        private void dispatcherTimer_Tick(object sender, EventArgs e)
        {
            SendBarcode();
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            this._joined = false;
            this.Channel = new UdpAnySourceMulticastChannel(GROUP_ADDRESS, GROUP_PORT);
            this.Channel.Joined += new EventHandler(Channel_Joined);
        }

        void Channel_Joined(object sender, EventArgs e)
        {
            this._joined = true;
            System.Diagnostics.Debug.WriteLine("joined");

            sendingTimer.Start();
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            sendingTimer.Stop();

            try
            {
                cameraCaptureTask.Show();
            }
            catch (System.InvalidOperationException ex)
            {
                MessageBox.Show("An error occurred.");
            }
        }

        void cameraCaptureTask_Completed(object sender, PhotoResult e)
        {
            if (e.TaskResult == TaskResult.OK)
            {
                System.Windows.Media.Imaging.BitmapImage bmp = new System.Windows.Media.Imaging.BitmapImage();
                bmp.SetSource(e.ChosenPhoto);
                WP7BarcodeManager.ScanBarcode(bmp, Finished_Processing);
            }
        }

        private void SendBarcode()
        {
            if (this._joined && code128.Length > 0)
            {
                System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
                this.Channel.SendBytes(encoding.GetBytes(code128));
                System.Diagnostics.Debug.WriteLine("Sending " + code128);
            }
        }

        public void Finished_Processing(BarcodeCaptureResult result)
        {

            if (WP7BarcodeManager.LastCaptureResults.BarcodeImage != null)
                image1.Source = WP7BarcodeManager.LastCaptureResults.BarcodeImage;

            
            if (result.State == WP7_Barcode_Library.CaptureState.Success)
            {
                this.textBox1.Text = result.BarcodeText;
                code128 = result.BarcodeText;

                if (!this._joined)
                    this.Channel.Open();
            }
            else
            {
                this.textBox1.Text = "Try again. Error: "+ result.State;
                code128 = string.Empty;
                sendingTimer.Stop();
            }
        }

        private void button2_Click(object sender, RoutedEventArgs e)
        {
            if (code128.Length > 0)
            {
                webBrowserTask.Uri = new Uri("http://www.posti.fi/itemtracking/posti/search_by_shipment_id?lang=fi&ShipmentId=" + Uri.EscapeDataString(code128), UriKind.Absolute);
                webBrowserTask.Show();
            }
            else
            {
                MessageBox.Show("Read barcode first");
            }
        }

    }
}